<template>
  <div class="app-container">
    <!-- 搜索和操作区域保持不变 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="食谱名称" prop="recipeName">
        <el-input
          v-model="queryParams.recipeName"
          placeholder="请输入食谱名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:recipe:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Postcard"
          @click="handleNotVerify"
          v-hasPermi="['manage:recipe:list']"
          >待审核食谱</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="WarnTriangleFilled"
          @click="handleRejected"
          v-hasPermi="['manage:recipe:list']"
          >被驳回食谱</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 卡片展示区域 -->
    <el-row :gutter="20" class="card-row">
      <el-col
        :span="6"
        v-for="recipe in recipeList"
        :key="recipe.recipeId"
        class="mb-20"
      >
        <el-card class="recipe-card">
          <div class="recipe-card__header">
            <span class="recipe-card__title">{{ recipe.recipeName }}</span>
            <div class="recipe-card__actions">
              <!-- 咨询按钮 -->
              <el-tooltip content="咨询" placement="top">
                <el-button
                  type="success"
                  link
                  icon="ChatRound"
                  @click="handleConsult(recipe)"
                  v-hasPermi="['manage:recipe:edit']"
                ></el-button>
              </el-tooltip>
              <!-- 咨询回复按钮 -->
              <el-tooltip
                content="咨询回复"
                placement="top"
                v-if="recipe.newRecipe"
              >
                <el-button
                  type="info"
                  link
                  icon="ChatLineRound"
                  @click="handleConsultReply(recipe)"
                  v-hasPermi="['manage:recipe:list']"
                ></el-button>
              </el-tooltip>
              <!-- 查看按钮 -->
              <el-tooltip content="查看" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="View"
                  @click="handleDetail(recipe)"
                  v-hasPermi="['manage:recipe:list']"
                ></el-button>
              </el-tooltip>
              <!-- 编辑按钮 -->
              <el-tooltip content="编辑" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(recipe)"
                  v-hasPermi="['manage:recipe:edit']"
                ></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(recipe)"
                  v-hasPermi="['manage:recipe:remove']"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="recipe-card__content">
            <p class="recipe-card__time">
              创建时间: {{ parseTime(recipe.createTime, "{y}-{m}-{d}") }}
            </p>
            <p class="recipe-card__remark">备注: {{ recipe.remark }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :pageSizes="pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食谱管理对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="recipeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食谱名称" prop="recipeName">
          <el-input v-model="form.recipeName" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeTab"
          @tab-click="handleTabClick"
          v-if="form.recipeId === null"
        >
          <el-tab-pane label="早餐食谱" name="breakfast">
            <template #default>
              <el-table
                :data="form.breakfastList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食材名称"
                  align="center"
                  prop="foodName"
                  width="150"
                >
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.foodName"
                      placeholder="请选择"
                      clearable
                      style="width: 120px"
                    >
                      <el-option
                        v-for="food in foodList"
                        :key="food.foodId"
                        :label="food.foodName"
                        :value="food.foodName"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'breakfast')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  link
                  icon="CirclePlus"
                  type="primary"
                  @click="handleAddItem('breakfast')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane label="午餐食谱" name="lunch">
            <template #default>
              <el-table
                :data="form.lunchList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食材名称"
                  prop="foodName"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.foodName"
                      placeholder="请选择"
                      clearable
                      style="width: 120px"
                    >
                      <el-option
                        v-for="food in foodList"
                        :key="food.foodId"
                        :label="food.foodName"
                        :value="food.foodName"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'lunch')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  link
                  icon="CirclePlus"
                  type="primary"
                  @click="handleAddItem('lunch')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
          <el-tab-pane label="晚餐食谱" name="dinner">
            <template #default>
              <el-table
                :data="form.dinnerList"
                style="width: 100%"
                :resizable="false"
              >
                <el-table-column
                  label="食材名称"
                  prop="foodName"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.foodName"
                      placeholder="请选择"
                      clearable
                      style="width: 120px"
                    >
                      <el-option
                        v-for="food in foodList"
                        :key="food.foodId"
                        :label="food.foodName"
                        :value="food.foodName"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="备注"
                  prop="remark"
                  align="center"
                  width="150"
                >
                  <template #default="scope">
                    <el-popover
                      placement="top-end"
                      :width="400"
                      trigger="manual"
                      :visible="scope.row.popoverVisible"
                    >
                      <el-input
                        type="textarea"
                        :rows="4"
                        placeholder="请输入内容"
                        v-model="scope.row.remark"
                      />
                      <div style="text-align: right; margin-top: 8px">
                        <el-button size="small" @click="closePopover(scope.row)"
                          >取 消</el-button
                        >
                        <el-button
                          type="primary"
                          size="small"
                          @click="confirmEdit(scope.row)"
                          >确 定</el-button
                        >
                      </div>
                      <template #reference>
                        <el-input
                          v-model="scope.row.remark"
                          placeholder="请输入备注"
                          @click="openPopover(scope.row)"
                        >
                        </el-input>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="scope">
                    <el-button
                      link
                      type="danger"
                      icon="Delete"
                      @click="handleRemoveItem(scope.$index, 'dinner')"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 按钮居中 -->
              <div
                style="display: flex; justify-content: center; margin-top: 10px"
              >
                <el-button
                  plain
                  icon="CirclePlus"
                  link
                  type="primary"
                  @click="handleAddItem('dinner')"
                  >新增</el-button
                >
              </div>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看食谱管理对话框 -->
    <el-dialog :title="title" v-model="detailOpen" width="600px" append-to-body>
      <el-tabs v-model="activeDetailTab" type="card" class="detail-tabs">
        <!-- 早餐食谱 -->
        <el-tab-pane label="早餐" name="breakfast">
          <div
            v-for="(item, index) in detailRecipe.breakfastRecipe"
            :key="`breakfast-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 午餐食谱 -->
        <el-tab-pane label="午餐" name="lunch">
          <div
            v-for="(item, index) in detailRecipe.lunchRecipe"
            :key="`lunch-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 晚餐食谱 -->
        <el-tab-pane label="晚餐" name="dinner">
          <div
            v-for="(item, index) in detailRecipe.dinnerRecipe"
            :key="`dinner-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 待审核食谱对话框 -->
    <el-dialog title="待审核食谱" v-model="verifyOpen" width="65%">
      <el-table :data="verifyRecipeList" v-loading="loading">
        <el-table-column prop="recipeName" label="食谱名称" width="150" />
        <el-table-column label="早餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.breakfastRecipe &&
                JSON.parse(scope.row.breakfastRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看早餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.breakfastRecipe)"
                  :key="`breakfast-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="
                      index < JSON.parse(scope.row.breakfastRecipe).length - 1
                    "
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无早餐数据</span>
          </template>
        </el-table-column>
        <el-table-column label="午餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.lunchRecipe &&
                JSON.parse(scope.row.lunchRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看午餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.lunchRecipe)"
                  :key="`lunch-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="index < JSON.parse(scope.row.lunchRecipe).length - 1"
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无午餐数据</span>
          </template>
        </el-table-column>
        <el-table-column label="晚餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.dinnerRecipe &&
                JSON.parse(scope.row.dinnerRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看晚餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.dinnerRecipe)"
                  :key="`dinner-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="index < JSON.parse(scope.row.dinnerRecipe).length - 1"
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无晚餐数据</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              link
              icon="Delete"
              @click="handleWithdraw(scope.row)"
              v-hasPermi="['manage:recipe:remove']"
              >撤回</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加分页组件 -->
      <pagination
        v-show="verifyTotal > 0"
        :total="verifyTotal"
        v-model:page="verifyQueryParams.pageNum"
        v-model:limit="verifyQueryParams.pageSize"
        @pagination="handleVerifyPageChange"
        align="center"
        :page-sizes="[5, 10]"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="verifyOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 被驳回食谱对话框 -->
    <el-dialog title="被驳回食谱" v-model="rejectedOpen" width="70%">
      <el-table :data="rejectedRecipeList" v-loading="loading">
        <el-table-column prop="recipeName" label="食谱名称" width="150" />
        <el-table-column label="早餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.breakfastRecipe &&
                JSON.parse(scope.row.breakfastRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看早餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.breakfastRecipe)"
                  :key="`breakfast-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="
                      index < JSON.parse(scope.row.breakfastRecipe).length - 1
                    "
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无早餐数据</span>
          </template>
        </el-table-column>
        <el-table-column label="午餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.lunchRecipe &&
                JSON.parse(scope.row.lunchRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看午餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.lunchRecipe)"
                  :key="`lunch-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="index < JSON.parse(scope.row.lunchRecipe).length - 1"
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无午餐数据</span>
          </template>
        </el-table-column>
        <el-table-column label="晚餐" width="120">
          <template #default="scope">
            <el-popover
              placement="right"
              width="400"
              trigger="click"
              v-if="
                scope.row.dinnerRecipe &&
                JSON.parse(scope.row.dinnerRecipe).length > 0
              "
            >
              <template #reference>
                <el-button link type="primary">查看晚餐</el-button>
              </template>
              <div class="meal-detail">
                <div
                  v-for="(item, index) in JSON.parse(scope.row.dinnerRecipe)"
                  :key="`dinner-${index}`"
                  class="meal-item"
                >
                  <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                  <p><strong>备注：</strong>{{ item.remark }}</p>
                  <el-divider
                    v-if="index < JSON.parse(scope.row.dinnerRecipe).length - 1"
                  />
                </div>
              </div>
            </el-popover>
            <span v-else>无晚餐数据</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="returnReason" label="驳回原因" width="200" />
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="rejectedTotal > 0"
        :total="rejectedTotal"
        v-model:page="rejectedQueryParams.pageNum"
        v-model:limit="rejectedQueryParams.pageSize"
        @pagination="handleRejectedPageChange"
        align="center"
        :page-sizes="[5, 10]"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectedOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 咨询对话框 -->
    <el-dialog :title="title" v-model="consultDialogVisible" width="500px">
      <el-form ref="consultRef" :model="consultForm" label-width="80px">
        <el-form-item label="营养师">
          <el-select
            v-model="consultForm.dietitianId"
            placeholder="请选择营养师"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="dietitian in dietitianList"
              :key="dietitian.userId"
              :label="dietitian.userName"
              :value="dietitian.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询内容" prop="consultBody">
          <el-input
            type="textarea"
            v-model="consultForm.consultBody"
            placeholder="请输入咨询内容"
            :rows="4"
            resize="none"
            show-word-limit
            maxlength="1000"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="consultDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDietitian">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="咨询回复"
      v-model="consultReplyOpen"
      width="600px"
      append-to-body
    >
      <el-tabs v-model="consultActiveTab" type="card" class="detail-tabs">
        <!-- 早餐食谱 -->
        <el-tab-pane label="早餐" name="newBreakfast">
          <div
            v-for="(item, index) in consultReplyData.breakfastRecipe"
            :key="`breakfast-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 午餐食谱 -->
        <el-tab-pane label="午餐" name="newLunch">
          <div
            v-for="(item, index) in consultReplyData.lunchRecipe"
            :key="`lunch-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 晚餐食谱 -->
        <el-tab-pane label="晚餐" name="newDinner">
          <div
            v-for="(item, index) in consultReplyData.dinnerRecipe"
            :key="`dinner-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
          </div>
        </el-tab-pane>

        <!-- 建议内容 -->
        <el-tab-pane label="建议" name="suggestion">
          <el-form-item label="建议内容" class="suggest-input">
            <el-input
              type="textarea"
              :rows="5"
              v-model="consultReplyData.suggestBody"
              placeholder="无建议内容"
              resize="none"
              readonly
            />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup name="Recipe">
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe } from "@/api/manage/recipe"
import { getUserListByRoleId } from "@/api/system/user"
import { listFood } from "@/api/manage/food"

const { proxy } = getCurrentInstance()

const recipeList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const pageSize = ref([12, 24, 36, 48])

const tabPosition = ref('left')
const activeTab = ref("breakfast")

const detailRecipe = ref({})
const activeDetailTab = ref('breakfast')
const consultActiveTab = ref('newBreakfast')

const data = reactive({
  form: {
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  },
  consultForm: {
    recipeId: null,
    dietitianId: null,
    consultBody: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 12,
    recipeName: null,
    verifyFlag: null,
    isVerifying: null
  },
  rules: {
    recipeName: [
      { required: true, message: '请输入食谱名称', trigger: 'blur' }
    ],
    breakfastList: [
      {
        validator: (rule, value, callback) => {
          // 检查是否有至少一个餐点有数据
          if (form.value.breakfastList.length === 0 &&
            form.value.lunchList.length === 0 &&
            form.value.dinnerList.length === 0) {
            callback(new Error('至少需要添加一种餐点的食谱'))
            return
          }

          // 检查每个餐点的数据是否有效
          const checkMealList = (list) => {
            return list.some(item => !item.foodName)
          }

          if (checkMealList(form.value.breakfastList) ||
            checkMealList(form.value.lunchList) ||
            checkMealList(form.value.dinnerList)) {
            callback(new Error('请为所有添加的食材选择食材名称'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  }
})

const { queryParams, form, consultForm, rules } = toRefs(data)

/** 查询食谱管理列表 */
function getList () {
  loading.value = true
  queryParams.value.verifyFlag = 1
  queryParams.value.isVerifying = 'user'
  listRecipe(queryParams.value).then(response => {
    recipeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    recipeId: null,
    recipeName: null,
    breakfastRecipe: null,
    lunchRecipe: null,
    dinnerRecipe: null,
    userId: null,
    createTime: null,
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  },
    consultForm.value = {
      recipeId: null,
      dietitianId: null,
      consultBody: null
    }
  proxy.resetForm("recipeRef")
  proxy.resetForm("consultRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.recipeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加食谱管理"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _recipeId = row.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改食谱管理"
  })
}

/** 查看按钮操作 */
function handleDetail (recipe) {
  const _recipeId = recipe.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    detailRecipe.value = response.data
    // 将json转换为数组
    detailRecipe.value.breakfastRecipe = JSON.parse(detailRecipe.value.breakfastRecipe)
    detailRecipe.value.lunchRecipe = JSON.parse(detailRecipe.value.lunchRecipe)
    detailRecipe.value.dinnerRecipe = JSON.parse(detailRecipe.value.dinnerRecipe)
    // 重置activeDetailTab为默认值
    activeDetailTab.value = 'breakfast'
    detailOpen.value = true
    // 修改标题为食谱名称
    title.value = "食谱名称：" + detailRecipe.value.recipeName || "食谱详情"
  })
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["recipeRef"].validate(valid => {
    if (valid) {
      // 检查是否有至少一个餐点有数据
      if (form.value.breakfastList.length === 0 &&
        form.value.lunchList.length === 0 &&
        form.value.dinnerList.length === 0) {
        proxy.$modal.msgError('至少需要添加一种餐点的食谱')
        return
      }

      // 检查每个餐点的数据是否有效
      const hasEmptyItem = (list) => {
        return list.some(item => !item.foodName)
      }

      if (hasEmptyItem(form.value.breakfastList) ||
        hasEmptyItem(form.value.lunchList) ||
        hasEmptyItem(form.value.dinnerList)) {
        proxy.$modal.msgError('请为所有添加的食材选择食材名称')
        return
      }

      if (form.value.recipeId != null) {
        updateRecipe(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 提取数据
        const recipeData = {}
        recipeData.recipeName = form.value.recipeName
        recipeData.remark = form.value.remark
        // 移除 popoverVisible 字段并转换为 JSON 字符串
        recipeData.breakfastRecipe = JSON.stringify(
          form.value.breakfastList.map(item => {
            const { popoverVisible, ...rest } = item
            return rest
          })
        )
        recipeData.lunchRecipe = JSON.stringify(
          form.value.lunchList.map(item => {
            const { popoverVisible, ...rest } = item
            return rest
          })
        )
        recipeData.dinnerRecipe = JSON.stringify(
          form.value.dinnerList.map(item => {
            const { popoverVisible, ...rest } = item
            return rest
          })
        )
        addRecipe(recipeData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _recipeIds = row.recipeId || ids.value
  const delName = _recipeIds.length >= 1 ? '选中的食谱' : row.recipeName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delRecipe(_recipeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/recipe/export', {
    ...queryParams.value
  }, `recipe_${new Date().getTime()}.xlsx`)
}

// 新增进食记录
function handleAddItem (mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.push({})
  } else if (mealType === 'lunch') {
    form.value.lunchList.push({})
  } else {
    form.value.dinnerList.push({})
  }
}

// 删除进食记录
function handleRemoveItem (index, mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.splice(index, 1)
  } else if (mealType === 'lunch') {
    form.value.lunchList.splice(index, 1)
  } else {
    form.value.dinnerList.splice(index, 1)
  }
}

const foodList = ref([])

// 获取食材列表
function getFoodList () {
  listFood().then(response => {
    foodList.value = response.rows
  })
}

// 打开 Popover
function openPopover (row) {
  if (!row.popoverVisible) {  // 防止重复打开
    row.popoverVisible = true
  }
};

function confirmEdit (row) {
  row.popoverVisible = false
};

// 关闭 Popover
function closePopover (row) {
  row.popoverVisible = false
  row.remark = null  // 清除输入内容
};

const verifyOpen = ref(false)
const verifyRecipeList = ref([])

// 添加待审核食谱分页相关变量
const verifyQueryParams = ref({
  pageNum: 1,
  pageSize: 5,
  verifyFlag: 0,
  isVerifying: null
})

const verifyTotal = ref(0)

// 修改handleNotVerify函数
function handleNotVerify () {
  verifyQueryParams.value.pageNum = 1
  verifyQueryParams.value.isVerifying = 'user'
  getVerifyList()
}

// 添加获取待审核列表函数
function getVerifyList () {
  loading.value = true
  listRecipe(verifyQueryParams.value).then(response => {
    verifyRecipeList.value = response.rows
    verifyTotal.value = response.total
    loading.value = false
    verifyOpen.value = true
  })
}

// 添加分页处理函数
function handleVerifyPageChange (val) {
  verifyQueryParams.value.pageNum = val.page
  verifyQueryParams.value.pageSize = val.limit
  getVerifyList()
}

const dietitianList = ref([])
const consultDialogVisible = ref(false)

function getDietitianList () {
  getUserListByRoleId(100).then(res => {
    dietitianList.value = res.data
  })
}

// 咨询按钮事件
function handleConsult (recipe) {
  consultForm.value.recipeId = recipe.recipeId
  getRecipe(recipe.recipeId).then(response => {
    consultForm.value.dietitianId = response.data.dietitianId
    consultForm.value.consultBody = response.data.consultBody
  })
  title.value = '选择营养师'
  consultDialogVisible.value = true
}

// 确认选择营养师
function confirmDietitian () {
  if (!consultForm.value) {
    proxy.$modal.msgWarning('请选择营养师')
    return
  }
  updateRecipe(consultForm.value).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("提交成功")
    } else {
      proxy.$modal.msgError(response.msg)
    }
    reset()
    consultDialogVisible.value = false
  })
}

const rejectedOpen = ref(false)
const rejectedRecipeList = ref([])
const rejectedTotal = ref(0)

const rejectedQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  verifyFlag: 2, // 2表示被驳回状态
  isVerifying: null
})

// 被驳回食谱按钮事件
function handleRejected () {
  rejectedQueryParams.value.pageNum = 1
  rejectedQueryParams.value.isVerifying = 'user'
  getRejectedList()
}

// 获取被驳回食谱列表
function getRejectedList () {
  loading.value = true
  listRecipe(rejectedQueryParams.value).then(response => {
    rejectedRecipeList.value = response.rows
    rejectedTotal.value = response.total
    loading.value = false
    rejectedOpen.value = true
  })
}

// 被驳回食谱分页处理
function handleRejectedPageChange (val) {
  rejectedQueryParams.value.pageNum = val.page
  rejectedQueryParams.value.pageSize = val.limit
  getRejectedList()
}

const consultReplyOpen = ref(false)
const consultReplyData = ref({})

// 处理咨询回复按钮点击
function handleConsultReply (recipe) {
  if (recipe.newRecipe) {
    consultReplyData.value = {
      breakfastRecipe: JSON.parse(recipe.newRecipe.breakfastRecipe || '[]'),
      lunchRecipe: JSON.parse(recipe.newRecipe.lunchRecipe || '[]'),
      dinnerRecipe: JSON.parse(recipe.newRecipe.dinnerRecipe || '[]'),
      suggestBody: recipe.suggestBody
    }
  } else {
    consultReplyData.value = {
      breakfastRecipe: [],
      lunchRecipe: [],
      dinnerRecipe: [],
      suggestBody: ''
    }
  }
  // 设置默认激活的tab为'breakfast'
  activeDetailTab.value = 'breakfast'
  consultReplyOpen.value = true
}

function handleWithdraw (row) {
  proxy.$modal.confirm('确定要撤回该食谱吗？').then(function () {
    return delRecipe(row.recipeId)
  }).then(() => {
    proxy.$modal.msgSuccess("撤回成功")
    getVerifyList() // 刷新待审核列表
  }).catch(() => { })
}

getList()
getFoodList()
getDietitianList()
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.card-row {
  margin-top: 20px; /* 增加卡片与顶部按钮的间距 */
}

.recipe-card {
  height: 120px; /* 缩小卡片高度 */
  width: 100%; /* 卡片宽度填满父容器 */
  display: flex;
  flex-direction: column;
  border-radius: 12px; /* 圆角 */
  overflow: hidden; /* 隐藏超出部分 */
  position: relative;
  background: linear-gradient(135deg, #f9f9f9, #e0e0e0); /* 渐变背景 */
  border: 1px solid rgba(0, 0, 0, 0.1); /* 边框 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 初始阴影 */
  transition: transform 0.3s ease, box-shadow 0.3s ease; /* 添加动画效果 */
}

.recipe-card:hover {
  transform: translateY(-5px); /* 悬停时卡片上移 */
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* 悬停时添加阴影 */
}

.recipe-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  /* 添加以下样式确保布局稳定 */
  min-width: 0; /* 解决flex布局下的溢出问题 */
}

.recipe-card__title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  /* 添加以下样式 */
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 110px; /* 设置最大宽度 */
  display: inline-block; /* 确保宽度限制生效 */
}

.recipe-card__actions {
  display: flex;
  /* 添加以下样式确保按钮不会被挤压 */
  flex-shrink: 0;
}

.recipe-card__content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.recipe-card__remark,
.recipe-card__time {
  font-size: 14px; /* 缩小字体大小 */
  margin: 4px 0; /* 减少间距 */
  color: #666; /* 文字颜色 */
}

.detail-section {
  margin-bottom: 20px;
}

.section-header {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

hr {
  margin: 10px 0;
  border: 0;
  border-top: 1px solid #ddd;
}

.meal-detail {
  padding: 10px;
}

.meal-item {
  margin-bottom: 10px;
}

.meal-item p {
  margin: 5px 0;
  font-size: 14px;
}

.recipe-item {
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.suggest-input {
  margin: 20px;
}

.suggest-input :deep(.el-form-item__content) {
  width: 100%;
}
</style>